package com.fingard.dsp.bank.directbank.pos01;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.SortHelper;
import com.zhongbaofu.util.Util;

public class POS01Base extends DirectBase {
	protected String getCharset(){
		return getBankConfig().getCharset("utf-8");
	}
	
	protected String getCharset(String p_def, String p_for){
		return getBankConfig().getCharset(p_def, p_for);
	}
	
	public Map<String, String> removeHead(Map<String, String> tmpMapParams) {
		tmpMapParams.remove("BankCode");
		tmpMapParams.remove("TransType");
		tmpMapParams.remove("CommandCode");
		tmpMapParams.remove("Entity");
		tmpMapParams.remove("POSRecChannel");
		return tmpMapParams;
	}
	
	protected String getSignStr(Map<String, String> mapParams) {
		Map<String, String> signMap = new HashMap<String, String>();

		for (Map.Entry<String, String> entry : mapParams.entrySet()) {
			String name = entry.getKey();
			String value = entry.getValue();

			if (StringHelper.hasAnyChar(value)) {
				signMap.put(name, value);
			}
		}

		// Map排序
		signMap = SortHelper.sortMapByName(signMap);

		// Map转HTTP字符串
		String signStr = "";
		for (String key : signMap.keySet()) {
			signStr += "&" + key + "=" + signMap.get(key);
		}
		signStr = signStr.substring(1);
		
		return signStr;
	}
	
	protected String[] sendToBank(String p_reqStr, String url) throws Exception{
		String[] retStr;
		WriteBankUrlLogLn(url);
		url += URLEncoder.encode(p_reqStr, getCharset());
		WriteBankLogStep2(p_reqStr);
		WebRequest tmpWebRequest = new WebRequest(url);
		tmpWebRequest.setConnectTimeout(60000);
		tmpWebRequest.setRequestProperty("connection", "Close");
		byte[] tmpUpBytes = p_reqStr.getBytes(getCharset());
		retStr = tmpWebRequest.upload(tmpUpBytes, getCharset());
		WriteBankLogStep3(retStr[1]);
		if(retStr[0].length() == 0){
			int tmpIndex = retStr[1].indexOf("<");
			if(tmpIndex > 0){
				retStr[1] = retStr[1].substring(tmpIndex);
			}
		}else{
			this.WriteBankLogLn(tmpWebRequest.sbLog);
		}
		return retStr;
	}
	boolean verifySignByRSA(String plain,String saltKey) throws Exception {
		String startTag = "<MAC>";
		String endTag = "</MAC>";
		if (plain.contains(startTag) && plain.contains(endTag)) {
			String tmpPlain = plain.replaceAll("<MAC>.+</MAC>", "");
			String mac = Util.xorAndGenMac(tmpPlain, saltKey);
			String retMac = plain.substring(plain.indexOf(startTag) + startTag.length(), plain.indexOf(endTag));
			if (mac.equals(retMac)) {
				return true;
			} else {
				return false;
			}
		}
		return false;
	}
}
